package com.example.yangguoying;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TabHost;
import android.widget.Toast;

import com.example.yangguoying.SqLiteDatabase.GetDatabase;
import com.example.yangguoying.adapter.StudentInfoAdapter;
import com.example.yangguoying.adapter.ViewPagerAdapter;
import com.example.yangguoying.datasource.DataSource;
import com.example.yangguoying.entity.StudentInfo;
import com.example.yangguoying.util.JDBC.JDBCAPI.JDBCUtilImpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener{
    ImageButton edit_button;
    SharedPreferences.Editor dataEdit;
    SharedPreferences getDataEdit;
    Button main_add_student_info;
    ListView main_student_info_list;
    StudentInfoAdapter studentInfoAdapter;
    List<StudentInfo> list;
    DataSource dataSource;
    JDBCUtilImpl jdbcUtil;
    GetDatabase database;
    SQLiteDatabase sqLiteDatabase;
    Cursor cursor;
    StudentInfo studentInfo;
    ContentValues contentValues;
    ProgressDialog progressDialog;
    Button view_one_button;
    Button view_tow_button;
    LinearLayout view_one_line;
    LinearLayout view_tow_line;
    Button cloud_view_button;
    List<StudentInfo> cloud_list;
    ListView cloud_view_list;
    StudentInfoAdapter cloudStudentInfoAdapter;

    private LayoutInflater layoutInflater;
    private ViewPager viewPager;
    private ViewPagerAdapter viewPagerAdapter;
    private List<View> viewList;
    private View viewOne;
    private View viewTow;
    private int curIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        setView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:
                onLoadStudentInfo();
                break;
            case 2:
            case 4:
            case 6:
                studentInfoAdapter.notifyDataSetChanged();
                break;
        }
    }

    private void initView() {
        edit_button = findViewById(R.id.edit_button);
        dataEdit = getSharedPreferences("user_data",MODE_PRIVATE).edit();
        getDataEdit = getSharedPreferences("user_data",MODE_PRIVATE);
        main_add_student_info = findViewById(R.id.main_add_student_info);
//        main_student_info_list = findViewById(R.id.main_student_info_list);
        dataSource = new DataSource();
        jdbcUtil = new JDBCUtilImpl(dataSource.getConnectionUrl(),dataSource.getDatabaseUser(),dataSource.getDatabasePassword(),"com.mysql.jdbc.Driver");
        database = new GetDatabase();
        sqLiteDatabase = database.getDatabase(this).getWritableDatabase();
        contentValues = new ContentValues();
        progressDialog = new ProgressDialog(MainActivity.this);
        view_one_button = findViewById(R.id.view_one_button);
        view_tow_button = findViewById(R.id.view_tow_button);
        view_one_line = findViewById(R.id.view_one_line);
        view_tow_line = findViewById(R.id.view_tow_line);


        layoutInflater = LayoutInflater.from(this);
        viewList = new ArrayList<>();
        viewPager = findViewById(R.id.view_pager);
        viewOne = layoutInflater.inflate(R.layout.local_database_view,null);
        viewTow = layoutInflater.inflate(R.layout.cloud_database_view,null);
        viewList.add(viewOne);
        viewList.add(viewTow);
        viewPagerAdapter = new ViewPagerAdapter(viewList);
        viewPager.setAdapter(viewPagerAdapter);
        viewPager.setCurrentItem(curIndex);
        viewPager.setOffscreenPageLimit(2);

        viewPager.addOnPageChangeListener(this);
        main_student_info_list =viewOne.findViewById(R.id.main_student_info_list);
        onLoadStudentInfo();
        cloud_view_button = viewTow.findViewById(R.id.cloud_view_button);
        cloud_view_list = viewTow.findViewById(R.id.cloud_view_list);
        cloudStudentInfoAdapter = new StudentInfoAdapter(MainActivity.this,cloud_list);

    }
    private void setView() {

        main_student_info_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this,ShowStudentInfoActivity.class);
                intent.putExtra("id",list.get(position).getId());
                intent.putExtra("isCloud",false);
                startActivityForResult(intent,2);
            }
        });

        main_add_student_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddStudentInfoActivity.class);
                startActivityForResult(intent, 1);
                finish();

            }
        });

        main_student_info_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示");
                builder.setMessage("确认删除学生信息");
                builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //TODO 删除本地数据
                        sqLiteDatabase.delete("student_info","student_info_id = ?",new String[]{String.valueOf(list.get(position).getId())});
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        AlertDialog.Builder builder_delete_cloud = new AlertDialog.Builder(MainActivity.this);
                        builder_delete_cloud.setTitle("提示");
                        builder_delete_cloud.setMessage("是否删除云数据信息");
                        builder_delete_cloud.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //TODO 删除云数据
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        jdbcUtil.deleteData("DELETE FROM `student_info` WHERE `student_info_id` = ?",new Object[]{list.get(position).getId()});
                                        deleteBefore(position);
                                    }
                                }).start();
                            }
                        });
                        builder_delete_cloud.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                deleteBefore(position);
                            }
                        });
                        builder_delete_cloud.show();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                builder.show();

                return true;
            }
        });

        studentInfoAdapter.setOnItemClickCallPhoneListener(new StudentInfoAdapter.OnCallPhoneListener() {
            @Override
            public void onCallPhoneClick(int i) {
                //TODO 打电话功能
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + list.get(i).getStudentPhone()));
                startActivity(intent);
            }
        });



        studentInfoAdapter.setOnItemClickModifyListener(new StudentInfoAdapter.OnModifyListener() {
            @Override
            public void onModifyClick(int i) {
                //TODO 修改学生信息功能
                Intent intent = new Intent(MainActivity.this,ModifyInfoActivity.class);
                //TODO 设置ID
                intent.putExtra("id",list.get(i).getId());
                startActivityForResult(intent,4);
            }
        });


        studentInfoAdapter.setOnItemClickUploadListener(new StudentInfoAdapter.OnUploadListener() {
            @Override
            public void onUploadClick(int i) {
                //TODO 上传数据到云数据看库
                contentValues.put("is_upload",1);
                sqLiteDatabase.update("student_info",contentValues,"student_info_id = ?",new String[]{String.valueOf(list.get(i).getId())});
                String sql = "INSERT INTO `student_info`(student_name,student_num,student_phone,student_address,student_faculty,student_grade,student_class,student_dormitory,student_remarks,is_upload) VALUES (" +
                        "?,?,?,?,?,?,?,?,?,?)";
                StudentInfo queryInfo = queryStudentInfo(list.get(i).getId());
                progressDialog.setTitle("上传中....");
//设置ProgressDialog 是否可以按返回键取消；
                progressDialog.setCancelable(true);
                progressDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
//显示ProgressDialog
                progressDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        jdbcUtil.updtateData(sql,new Object[]{
                                queryInfo.getStudentName(),queryInfo.getStudentNum(),queryInfo.getStudentPhone(),queryInfo.getStudentAddress(),queryInfo.getStudentFaculty(),queryInfo.getStudentGrade(),
                                queryInfo.getStudentClass(),queryInfo.getStudentDormitory(),queryInfo.getStudentRemarks(),queryInfo.getUpload()
                        });
                        showResponse(i);
                    }
                }).start();
            }
        });

        cloudStudentInfoAdapter.setOnItemClickUploadListener(new StudentInfoAdapter.OnUploadListener() {
            @Override
            public void onUploadClick(int i) {
                Toast.makeText(MainActivity.this,"已经在云数据库中，无需上传",Toast.LENGTH_SHORT).show();
            }
        });

        cloudStudentInfoAdapter.setOnItemClickModifyListener(new StudentInfoAdapter.OnModifyListener() {
            @Override
            public void onModifyClick(int i) {
                Toast.makeText(MainActivity.this,"暂不支持修改云数据库信息",Toast.LENGTH_SHORT).show();
            }
        });
        cloudStudentInfoAdapter.setOnItemClickCallPhoneListener(new StudentInfoAdapter.OnCallPhoneListener() {
            @Override
            public void onCallPhoneClick(int i) {
                //TODO 打电话功能
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + cloud_list.get(i).getStudentPhone()));
                startActivity(intent);
            }
        });

        cloud_view_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                AlertDialog.Builder builder_delete_cloud = new AlertDialog.Builder(MainActivity.this);
                builder_delete_cloud.setTitle("提示");
                builder_delete_cloud.setMessage("是否删除云数据信息");
                builder_delete_cloud.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //TODO 删除云数据
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                jdbcUtil.deleteData("DELETE FROM `student_info` WHERE `student_info_id` = ?",new Object[]{cloud_list.get(position).getId()});
                                deleteCloudBefore(position);
                            }
                        }).start();
                    }
                });
                builder_delete_cloud.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteBefore(position);
                    }
                });
                builder_delete_cloud.show();

                return true;
            }
        });

        cloud_view_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this,ShowStudentInfoActivity.class);
                intent.putExtra("id",cloud_list.get(position).getId());
                intent.putExtra("isCloud",true);
                startActivityForResult(intent,6);
            }
        });


        edit_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popupMenu = new PopupMenu(MainActivity.this,edit_button);
                popupMenu.getMenuInflater().inflate(R.menu.menu_pop,popupMenu.getMenu());
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()){
                            case R.id.clear_auto_login:
                                dataEdit.putBoolean("isAutoLogin",false);
                                dataEdit.commit();
                                break;
                            case R.id.exit_login:
                                dataEdit.putBoolean("isAutoLogin",false);
                                dataEdit.commit();
                                startActivity(new Intent(MainActivity.this,LoginActivity.class));
                                finish();
                                break;
                            default:
                                break;
                        }
                        return true;
                    }
                });
                popupMenu.show();
            }
        });
        view_one_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setCurrentItem(curIndex);
                view_one_line.setBackgroundColor(Color.parseColor("#03A9F4"));
                view_tow_line.setBackgroundColor(Color.parseColor("#FFFFFF"));
            }
        });
        view_tow_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setCurrentItem(1);
                view_one_line.setBackgroundColor(Color.parseColor("#FFFFFF"));
                view_tow_line.setBackgroundColor(Color.parseColor("#03A9F4"));
            }
        });

        //下载数据
        cloud_view_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cloud_list = new ArrayList<>();
                progressDialog.setTitle("加载中....");
//设置ProgressDialog 是否可以按返回键取消；
                progressDialog.setCancelable(true);
                progressDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
//显示ProgressDialog
                progressDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        ResultSet resultSet = jdbcUtil.queryData("SELECT * FROM student_info", null);
                        try {
                            while (resultSet.next()){
                                StudentInfo cloudStudentInfo = new StudentInfo(resultSet.getInt("student_info_id"),resultSet.getString("student_name"),resultSet.getString("student_num")
                                        ,resultSet.getString("student_phone"),resultSet.getString("student_address"),resultSet.getString("student_faculty"),resultSet.getString("student_grade")
                                        ,resultSet.getString("student_class"),resultSet.getString("student_dormitory"),resultSet.getString("student_remarks"),resultSet.getInt("is_upload"));
                                cloud_list.add(cloudStudentInfo);
                            }
                        }catch (SQLException e) {
                            e.printStackTrace();
                        }
                       showCloudView(cloud_list);
                    }
                }).start();
            }
        });
    }
    private  void onLoadStudentInfo(){
        //TODO 加载本地数据
        list = new ArrayList<>();
        cursor = sqLiteDatabase.query("student_info",null,null,null,null,null,null);
        if (cursor.moveToFirst()){
            do {
                int studentInfoId = cursor.getInt(cursor.getColumnIndex("student_info_id"));
                String studentName = cursor.getString(cursor.getColumnIndex("student_name"));
                String studentNum = cursor.getString(cursor.getColumnIndex("student_num"));
                String studentPhone = cursor.getString(cursor.getColumnIndex("student_phone"));
                String studentAddress = cursor.getString(cursor.getColumnIndex("student_address"));
                String studentFaculty = cursor.getString(cursor.getColumnIndex("student_faculty"));
                String studentGrade = cursor.getString(cursor.getColumnIndex("student_grade"));
                String studentClass = cursor.getString(cursor.getColumnIndex("student_class"));
                String studentDormitory = cursor.getString(cursor.getColumnIndex("student_dormitory"));
                String studentRemarks = cursor.getString(cursor.getColumnIndex("student_remarks"));
                int isUpload = cursor.getInt(cursor.getColumnIndex("is_upload"));
                studentInfo = new StudentInfo(studentInfoId,studentName,studentNum,studentPhone,studentAddress,studentFaculty,studentGrade,studentClass,studentDormitory,studentRemarks,isUpload);
                list.add(studentInfo);
            }while (cursor.moveToNext());
        }
        studentInfoAdapter = new StudentInfoAdapter(this,list);
        main_student_info_list.setAdapter(studentInfoAdapter);
        studentInfoAdapter.notifyDataSetChanged();
    }

    private StudentInfo queryStudentInfo(int id){
        StudentInfo queryInfo = null;
        cursor = sqLiteDatabase.query("student_info",null,"student_info_id = ?",new String[]{String.valueOf(id)},null,null,null,null);
        if (cursor.moveToFirst()) {
            do {
                int studentInfoId = cursor.getInt(cursor.getColumnIndex("student_info_id"));
                String studentName = cursor.getString(cursor.getColumnIndex("student_name"));
                String studentNum = cursor.getString(cursor.getColumnIndex("student_num"));
                String studentPhone = cursor.getString(cursor.getColumnIndex("student_phone"));
                String studentAddress = cursor.getString(cursor.getColumnIndex("student_address"));
                String studentFaculty = cursor.getString(cursor.getColumnIndex("student_faculty"));
                String studentGrade = cursor.getString(cursor.getColumnIndex("student_grade"));
                String studentClass = cursor.getString(cursor.getColumnIndex("student_class"));
                String studentDormitory = cursor.getString(cursor.getColumnIndex("student_dormitory"));
                String studentRemarks = cursor.getString(cursor.getColumnIndex("student_remarks"));
                int isUpload = cursor.getInt(cursor.getColumnIndex("is_upload"));
                queryInfo = new StudentInfo(studentInfoId,studentName,studentNum,studentPhone,studentAddress,studentFaculty,studentGrade,studentClass,studentDormitory,studentRemarks,isUpload);
            } while (cursor.moveToNext());

        }
        return  queryInfo;
    }

    private void showResponse(int i) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                list.get(i).setUpload(1);
                studentInfoAdapter.notifyDataSetChanged();
                progressDialog.cancel();
               Toast.makeText(MainActivity.this,"上传成功！",Toast.LENGTH_SHORT).show();

            }
        });


    }



    private void deleteBefore(int i) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                list.remove(i);
                studentInfoAdapter.notifyDataSetChanged();
                Toast.makeText(MainActivity.this,"删除成功!",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void deleteCloudBefore(int i) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                cloud_list.remove(i);
                studentInfoAdapter.notifyDataSetChanged();
                Toast.makeText(MainActivity.this,"删除成功!",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showCloudView(List<StudentInfo> cloud_list) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                cloudStudentInfoAdapter.setList(cloud_list);
                cloud_view_list.setAdapter(cloudStudentInfoAdapter);
                cloudStudentInfoAdapter.notifyDataSetChanged();
                progressDialog.cancel();
            }
        });
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position){
            case 0:
                view_one_line.setBackgroundColor(Color.parseColor("#03A9F4"));
                view_tow_line.setBackgroundColor(Color.parseColor("#FFFFFF"));
                break;
            case 1:
                view_one_line.setBackgroundColor(Color.parseColor("#FFFFFF"));
                view_tow_line.setBackgroundColor(Color.parseColor("#03A9F4"));
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
}